<?php
!function_exists('adminmsg') && exit('Forbidden');
$brokerGroupService = House::loadService('brokerGroupService');
if (!$action) {
	$groups = $brokerGroupService->getBrokerGroups();
	$ajaxUrl = EncodeUrl($basename);
	require_once PrintMode('brokergroup.run');
} elseif ($action == 'edit') {
	InitGP(array('groupid','step'),'',2);

	$groupInfo = $brokerGroupService->getBrokerGroup($groupid);
	if (!$groupInfo) Error::showError('群组信息有误');
	
	if ($step == 2) {
		InitGP(array('right'));
		$right['ifsale'] = (int) $right['ifsale'];
		$right['salenum'] = intval($right['salenum']) < 0 ? 0 : intval($right['salenum']);
		$right['ifhire'] = (int) $right['ifhire'];
		$right['hirenum'] = intval($right['hirenum']) < 0 ? 0 : intval($right['hirenum']);
		
		$brokerGroupService->updateBrokerGroupRight($groupid,$right);
		adminmsg('操作成功！');
	} else {
		$groups = $brokerGroupService->getBrokerGroups();
		ifcheck($groupInfo['right']['ifsale'], 'ifsale');
		ifcheck($groupInfo['right']['ifhire'], 'ifhire');

		require_once PrintMode('brokergroup.edit');
	}
} elseif ($action =='update') {
	InitGP(array('name','add'));
	$groups = array();
	foreach ($name as $key=>$value) {
		if (!$value) Error::addError('经纪人组名称不能为空');
		checkGroupName($value);
		$groups[] = array('groupid'=>$key,'name'=>$value);
	}
	
	$addGroups = array();
	foreach ($add as $key=>$value) {
		if (!$value) continue;
		checkGroupName($value);
		$addGroups[] = array('name'=>$value);
	}
	Error::checkError();

	$brokerGroupService->updateBrokerGroups($groups);
	$brokerGroupService->addBrokerGroups($addGroups);
	adminmsg('操作成功！');
} elseif ($action == 'delete') {
	InitGP(array('groupid'),'',2);
	define('AJAX',1);
	$groupInfo = $brokerGroupService->getBrokerGroup($groupid);
	if (!$groupInfo) Error::showError('error');
	if ($groupInfo['usernum']) Error::showError('haveuser');
	
	$brokerGroupService->deleteBrokerGroup($groupid);
	adminmsg('success');
}


function checkGroupName($name) {
	if (strlen($name)>30) {
		Error::addError($name.'字符过长');
		return false;
	}
	return true;
}
?>